package me.leiusual.sharing.ui.mine

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.core.content.FileProvider
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_mine_auth.*
import me.leiusual.sharing.BuildConfig
import me.leiusual.sharing.R
import me.leiusual.sharing.api.model.RealNameQuery
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.util.extension.*
import me.leiusual.sharing.util.tool.UriUtil
import timber.log.Timber
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject

/**
 * Create by leiusual on 2018/7/16
 */
class MineAuthFragment : DaggerFragment() {

  companion object {
    private const val REQ_PHOTO_FRONT_TAKE = 11
    private const val REQ_PHOTO_FRONT_PICK = 12
    private const val REQ_PHOTO_BACK_TAKE = 21
    private const val REQ_PHOTO_BACK_PICK = 22

    private const val CURRENT_PHOTO_PATH = "currentPhotoPath"
  }

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val viewModel: MineAuthViewModel by viewModels { factory }

  private var currentPhotoPath: String? = null

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    if (savedInstanceState != null && savedInstanceState.containsKey(CURRENT_PHOTO_PATH)) {
      currentPhotoPath = savedInstanceState.getString(CURRENT_PHOTO_PATH)
    }
  }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_mine_auth, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }

    // no
    text_view_mobile.text = "验证码将发送到您${viewModel.user.mobile.toImplicitMobile()}到手机上"

    image_view_front.setOnClickListener {
      startSelectImage(10)
    }

    image_view_back.setOnClickListener {
      startSelectImage(20)
    }

    text_view_send_sms.setOnClickListener {
      viewModel.sendSMS(viewModel.user.mobile)
    }

    // pending
    button_pending_back.setOnClickListener {
      findNavController().popBackStack()
    }

    // success

    // fail
    button_fail_back.setOnClickListener {
      layout_auth_fail.visibility = View.GONE
      nested_scroll_view.visibility = View.VISIBLE
    }

    button_confirm.setOnClickListener {
      val realName = edit_text_name.text.toString()
      val idCard = edit_text_id_card.text.toString()
      val checkCode = edit_text_code.text.toString()
      viewModel.realName(realName, idCard, checkCode)
    }

    observeData()

    viewModel.realNameQuery()
  }

  override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)
    outState.putString(CURRENT_PHOTO_PATH, currentPhotoPath)
  }

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    Timber.v("onActivityResult data = %s", data)

    if (resultCode == Activity.RESULT_OK) {
      when (requestCode) {
        REQ_PHOTO_FRONT_TAKE -> {
          viewModel.setFilePathFront(currentPhotoPath ?: return)
        }
        REQ_PHOTO_FRONT_PICK -> {
          currentPhotoPath = UriUtil.getPath(context, data?.data ?: return) ?: return
          viewModel.setFilePathFront(currentPhotoPath ?: return)
        }
        REQ_PHOTO_BACK_TAKE -> {
          viewModel.setFilePathBack(currentPhotoPath ?: return)
        }
        REQ_PHOTO_BACK_PICK -> {
          currentPhotoPath = UriUtil.getPath(context, data?.data ?: return) ?: return
          viewModel.setFilePathBack(currentPhotoPath ?: return)
        }
      }
    }
  }

  private fun startSelectImage(requestCode: Int) {
    context?.let {
      AlertDialog.Builder(it)
          .setItems(arrayOf("拍照", "相册", "取消")) { _, which ->
            when (which) {
              0 -> {
                val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                if (intent.resolveActivity(it.packageManager) != null) {
                  val photoFile = createImageFile(it) ?: return@setItems
                  val authority = BuildConfig.APPLICATION_ID + ".fileProvider"
                  val photoUri = FileProvider.getUriForFile(it, authority, photoFile)
                  intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
                  startActivityForResult(intent, requestCode + 1)
                }
              }
              1 -> {
                val intent = Intent(Intent.ACTION_GET_CONTENT)
                intent.type = "image/*"
                if (intent.resolveActivity(it.packageManager) != null) {
                  startActivityForResult(intent, requestCode + 2)
                }
              }
            }
          }
          .show()
    }
  }

  private fun observeData() {
    viewModel.realNameQuery.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("realNameQuery = %s", it)
      when (it) {
        is Data.Loading -> {
          content_loading_progress_bar.show()
        }
        is Data.Error -> {
          content_loading_progress_bar.hide()
          toast(it.error.message)
        }
        is Data.Success -> {
          content_loading_progress_bar.hide()
          when (it.data.auditStatus) {
            RealNameQuery.Status.NOT_APPLY -> {
              nested_scroll_view.visibility = View.VISIBLE
            }
            RealNameQuery.Status.AUDITING -> {
              layout_auth_pending.visibility = View.VISIBLE
            }
            RealNameQuery.Status.AUDIT_SUCCESS -> {
              layout_auth_info.visibility = View.VISIBLE
              text_view_real_name.text = it.data.name.toImplicitRealName()
              text_view_id_card.text = it.data.cardNo.toImplicitIdCard()
            }
            RealNameQuery.Status.AUDIT_FAIL -> {
              layout_auth_fail.visibility = View.VISIBLE
              text_view_fail_message_desc.text = "实名认证失败，原因如下：\n${it.data.auditNote}"
            }
          }
        }
      }
    })

    viewModel.sendSMS.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("sendSMS = %s", it)
      when (it) {
        is Data.Loading -> {
          text_view_send_sms.isEnabled = false
        }
        is Data.Error -> {
          text_view_send_sms.isEnabled = true
          toast(it.error.message)
        }
        is Data.Success -> {
          text_view_send_sms.startTimber()
          toast("短信发送成功")
        }
      }
    })

    viewModel.realName.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("realName = %s", it)
      when (it) {
        is Data.Loading -> {
          button_confirm.isEnabled = false
        }
        is Data.Error -> {
          button_confirm.isEnabled = true
          toast(it.error.message)
        }
        is Data.Success -> {
          toast("上传成功")
          findNavController().popBackStack()
        }
      }
    })

    viewModel.filePathFront.observe(viewLifecycleOwner, Observer {
      Timber.v("filePathFront = %s", it)
      image_view_front.setImageUrl(it)
    })

    viewModel.filePathBack.observe(viewLifecycleOwner, Observer {
      Timber.v("filePathBack = %s", it)
      image_view_back.setImageUrl(it)
    })
  }

  private fun createImageFile(context: Context): File? {
    try {
      val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(Date())
      val imageFileName = "JPEG_${timeStamp}_"
      val storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
      val image = File.createTempFile(imageFileName, ".jpg", storageDir)
      currentPhotoPath = image.absolutePath
      return image
    } catch (e: Throwable) {
      e.printStackTrace()
    }
    return null
  }
}